package com.kuaimacode.kframework.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase;
import com.kuaimacode.kframework.util.DateUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

public class AppolloDateSerializer extends DateTimeSerializerBase<Date> {

    public AppolloDateSerializer() {
        this(false, (DateFormat) null);
    }

    public AppolloDateSerializer(boolean useTimestamp, DateFormat customFormat) {
        super(Date.class, useTimestamp, customFormat);
    }

    @Override
    public DateTimeSerializerBase<Date> withFormat(Boolean timestamp, DateFormat customFormat) {
        return timestamp != null && timestamp ? new AppolloDateSerializer(true, null)
                : new AppolloDateSerializer(false, customFormat);
    }

    @Override
    protected long _timestamp(Date value) {
        return value == null ? 0L : value.getTime();
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        if (this._useTimestamp) {
            jgen.writeNumber(this._timestamp(value));
        } else if (this._customFormat != null) {
            this._customFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            synchronized (this._customFormat) {
                jgen.writeString(this._customFormat.format(value));
            }
        } else {
            jgen.writeString(DateUtil.format(value, DateUtil.DATE_FORMATE_STRING_A));
        }
    }
}
